package cn.xiaoliu.hrm.service.impl;

import cn.xiaoliu.hrm.domain.VipUser;
import cn.xiaoliu.hrm.dto.SmsCodeDto;
import cn.xiaoliu.hrm.mapper.VipUserMapper;
import cn.xiaoliu.hrm.service.IVerifyService;
import cn.xiaoliu.hrm.util.AjaxResult;
import cn.xiaoliu.hrm.util.ValidUtils;
import cn.xiaoliu.hrm.util.VerifyCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import sun.misc.BASE64Encoder;

import javax.validation.Valid;
import javax.validation.constraints.NotBlank;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class VerifyServiceImpl implements IVerifyService {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private VipUserMapper vipUserMapper;
    //图片验证码
    @Override
    public AjaxResult imageCode(String key) {
        try {
            //参数校验
            ValidUtils.assertNotNull(key,"验证码获取异常" );
            //获取验证码，然后存到redis
            String verifyCode = VerifyCodeUtils.generateVerifyCode(4).toLowerCase();
            redisTemplate.opsForValue().set(key,verifyCode ,5L , TimeUnit.MINUTES );

            //生成验证码图片，转成字符串到前端解析
            BASE64Encoder encoder = new BASE64Encoder();
            ByteArrayOutputStream data = new ByteArrayOutputStream();
            VerifyCodeUtils.outputImage(100,40 ,data ,verifyCode );
            return AjaxResult.me().setResultObj(encoder.encode(data.toByteArray()));
        } catch (IOException e) {
            e.printStackTrace();
            return AjaxResult.me().setSuccess(false).setMessage("操作失败");
        }
    }
    //验证码发送和校验
    @Override
    public AjaxResult sendSmsCode(@Valid SmsCodeDto dto) {
        //接口已经采用jsr303校验了
        //判断一下手机号是否被注册
        VipUser vipUser = new VipUser();
        vipUser.setPhone(dto.getMobile());
        VipUser user = vipUserMapper.selectOne(vipUser);
        if (user!=null){
            throw new RuntimeException("手机号已经注册过了,请直接登录");
        }
        //校验验证码
        String imageCode = dto.getImageCode();
        Object smsCode = redisTemplate.opsForValue().get(dto.getImageCodeKey());
        //首先看redis里面有没有，如果过期了就没有
        if (smsCode==null){
            throw new RuntimeException("验证码过期，请重新获取");
        }
        //再把redis里面的和前端输入的比较
        if (!imageCode.equalsIgnoreCase(smsCode.toString())){
            throw new RuntimeException("验证码输入有误，请重新输入");
        }
        //获取手机验证码
        String phoneCode = VerifyCodeUtils.generateVerifyCode(6, "0123456789");
        //存到redis中
        redisTemplate.opsForValue().set("REGISTE::"+dto.getMobile(),phoneCode ,3L,TimeUnit.MINUTES);
        System.out.println("您的验证码为："+phoneCode);
        return AjaxResult.me().setMessage("验证码获取成功，请及时输入");
    }
}
